package com.youth.routercore

import android.util.Log
import androidx.core.net.toUri
import com.example.lib_router.BuildConfig


const val youthHttpPath = "youth_app://youth.cn/"
const val youthHttpPath2 = "youthapp://youth.cn/"

internal fun <T> T.logd(tag: String = ""): T {
    if (BuildConfig.DEBUG) {
        val realTag = tag.ifEmpty { "Router_Youth" }
        if (this is Throwable) {
            Log.d(realTag, this.message ?: "", this)
        } else {
            Log.d(realTag, this.toString())
        }
    }
    return this
}

internal fun <T> T.logw(tag: String? = null): T? {
    val realTag = tag?.ifEmpty { "Router_Youth" }
    if (BuildConfig.DEBUG) {
        if (this is Throwable) {
            Log.w(realTag, this.message ?: "", this)
        } else {
            Log.w(realTag, this.toString())
        }
    }

    return this
}


internal fun parseScheme(scheme: String): String {
    val index = scheme.indexOfFirst { '?' == it }
    return when {
        scheme.startsWith(youthHttpPath) -> {
            val l = youthHttpPath.length
            val str = if (index > l) {
                scheme.substring(l, index)
            } else {
                scheme.substring(l)
            }
            str
        }
        scheme.startsWith(youthHttpPath2) -> {
            val l = youthHttpPath2.length
            val str = if (index > l) {
                scheme.substring(l, index)
            } else {
                scheme.substring(l)
            }
            str
        }
        else -> {
            return if (index > 0) {
                scheme.substring(0, index)
            } else {
                scheme
            }
        }
    }
}

internal fun parseSchemeParams(scheme: String): Array<Pair<String, Any?>> {
    "scheme=$scheme".logw("parseSchemeParams")

    val uri = scheme.toUri()
    "uri=$uri".logw("parseSchemeParams")
    val query = uri.query
    "query=$query".logw("parseSchemeParams")

    if (query != null) {
        val result = mutableListOf<Pair<String, Any?>>()
        uri.queryParameterNames.forEach {
//                        "it=$it , value=$value".logw("queryParameterNames")
            when (val value = uri.getQueryParameter(it)) {
                "true" -> {
                    result.add(it to true)
                }
                "false" -> {
                    result.add(it to false)
                }
                else -> {
                    result.add(it to value)
                }
            }
        }
        return result.toTypedArray()
    }
    return arrayOf()
}
